package com.rgst.serivce.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.rgst.dao.entity.BusiConfig;
import com.rgst.dao.repository.BusiConfigRepository;
import com.rgst.serivce.BusiConfigService;

/**
 * Created by tancw on 2019/12/22.
 */
@Service
public class BusiConfigServiceImpl implements BusiConfigService {
    @Autowired
    private BusiConfigRepository busiConfigRepository;

    @Override
    public List<BusiConfig> findAllGradeByTypeAndLikeTitle(String type, String likeTitle) {
        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                List<Predicate> predicatesList = new ArrayList<>();
                predicatesList.add(cb.equal(root.get("state"), 1));
                predicatesList.add(cb.equal(root.get("type"), type));
                predicatesList.add(cb.like(root.get("title"), likeTitle + "_%"));
                Predicate[] predicates = new Predicate[predicatesList.size()];
                return cb.and(predicatesList.toArray(predicates));
            }
        };
        return busiConfigRepository.findAll(specification, new Sort(Sort.Direction.ASC, "sno"));
    }

    @Override
    public List<BusiConfig> findAllByType(String type) {
        return busiConfigRepository.findAllByType(type);
    }
}
